import 'dart:convert';
import 'dart:io';

import 'package:ac/common/style.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/page/ac_me/ac_me_logic.dart';
import 'package:ac/widget/ac_app_bar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:extended_list/extended_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:rongcloud_im_wrapper_plugin/src/rongcloud_im_classes.dart';
import 'package:svgaplayer_flutter/player.dart';

import 'ac_chat_logic.dart';

class AcChatPage extends StatelessWidget {
  final logic = Get.find<AcChatLogic>();
  final state = Get.find<AcChatLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          appBar: AcAppbar(
            title: (state.conversation.value?.userinfo.nickname ?? "")
                .fixAutoLines(),
            actions: [
              Visibility(
                visible: state.conversation.value?.userinfo.userId !=
                    Get.find<AcMeLogic>().strategyModel.userServiceAccountId,
                child: GestureDetector(
                  onTap: logic.moreUtil.show,
                  child: Image.asset(
                    "images/icon_more2.png",
                    width: 28.w,
                  ),
                ),
              ),
              SizedBox(width: 15.w)
            ],
          ),
          backgroundColor: const Color(0xfff6f7f8),
          body: Column(
            children: [
              Expanded(
                child: Listener(
                  onPointerUp: (event) {
                    FocusScope.of(context).unfocus();
                    state.showMore.value = false;
                  },
                  child: Obx(() {
                    return ExtendedListView.builder(
                      itemBuilder: (c, i) {
                        var message = state.messages[i];
                        return _messageItem(message);
                      },
                      itemCount: state.messages.length,
                      reverse: true,
                      extendedListDelegate: const ExtendedListDelegate(
                        closeToTrailing: true,
                      ),
                    );
                  }),
                ),
              ),
              Container(
                height: 50.h,
                padding: EdgeInsets.only(
                  left: 15.w,
                  right: 15.w,
                ),
                width: double.infinity,
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        state.showVoice.value = !state.showVoice.value;
                      },
                      child: Image.asset(
                        "images/icon_voice.png",
                        width: 32.w,
                      ),
                    ),
                    SizedBox(width: 10.w),
                    Expanded(
                      child: Container(
                        height: 32.h,
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(horizontal: 12.w),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.w),
                          color: Colors.white,
                        ),
                        child: Obx(() {
                          return Visibility(
                            visible: !state.showVoice.value,
                            replacement: GestureDetector(
                              onPanDown: (d) {
                                logic.startRecorder();
                              },
                              onPanUpdate: (d) {
                                debugPrint('update ${d.localPosition}');
                                state.voiceValid.value =
                                    d.localPosition.dy > -150;
                              },
                              onPanCancel: () {
                                logic.stopRecorder();
                              },
                              onPanEnd: (d) {
                                logic.stopRecorder();
                              },
                              behavior: HitTestBehavior.opaque,
                              child: Padding(
                                padding: EdgeInsets.symmetric(vertical: 6.h),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      "Hold to talk",
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        color: textColorBlack,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            child: TextField(
                              controller: state.inputController,
                              style: TextStyle(
                                color: textColorBlack,
                                fontSize: 12.sp,
                                fontFamily: 'Inter',
                                fontWeight: FontWeight.w400,
                              ),
                              focusNode: state.focusNode,
                              decoration: InputDecoration(
                                hintText: "Type a message",
                                hintStyle: TextStyle(
                                  color: Colors.black.withOpacity(0.3),
                                  fontSize: 12.sp,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                ),
                                border: InputBorder.none,
                                isCollapsed: true,
                                isDense: true,
                              ),
                            ),
                          );
                        }),
                      ),
                    ),
                    SizedBox(width: 20.w),
                    Obx(() {
                      return Visibility(
                        visible: !state.showSend.value,
                        replacement: GestureDetector(
                          onTap: logic.sendTextMsg,
                          child: Container(
                            height: 32.h,
                            width: 63.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(32.w),
                              gradient: const LinearGradient(
                                colors: [
                                  Color(0xFFFFC371),
                                  Color(0xFFFF5F6D),
                                ],
                                begin: Alignment.centerLeft,
                                end: Alignment.centerRight,
                              ),
                            ),
                            child: Text(
                              "Send",
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                                fontFamily: 'Inter',
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                        ),
                        child: GestureDetector(
                          onTap: () {
                            FocusScope.of(context).unfocus();
                            state.showMore.value = !state.showMore.value;
                          },
                          child: Image.asset(
                            "images/icon_add2.png",
                            width: 32.w,
                          ),
                        ),
                      );
                    }),
                  ],
                ),
              ),
              SafeArea(
                top: false,
                child: Obx(() {
                  return Visibility(
                    visible: state.showMore.value,
                    child: GestureDetector(
                      onTap: logic.sendImageMsg,
                      child: Container(
                          height: 70.h,
                          padding: EdgeInsets.only(
                            left: 15.w,
                            right: 15.w,
                          ),
                          child: Row(
                            children: [
                              Image.asset(
                                "images/icon_image.png",
                                width: 42.w,
                              ),
                            ],
                          )),
                    ),
                  );
                }),
              )
            ],
          ),
        ),
        _voiceWidget(),
      ],
    );
  }

  Container _messageItem(RCIMIWMessage message) {
    var isMe =
        message.senderUserId != state.conversation.value?.userinfo.userId;
    var avatar = !isMe
        ? state.conversation.value?.userinfo.avatarThumbUrl
        : AcUserManager.userInfoModel?.userInfo.avatarMiddleThumbUrl;
    var translationStatus = message.expansion?["translationStatus"] ?? 0;
    var childChildren = [
      _content(message, isMe),
      if (!isMe) ...[
        SizedBox(width: 8.w),
        if (translationStatus != 2 &&
            message.messageType == RCIMIWMessageType.text)
          GestureDetector(
            onTap: () {
              logic.translation(message as RCIMIWTextMessage);
            },
            child: Container(
              margin: EdgeInsets.only(top: 10.h),
              child: Image.asset(
                "images/icon_resend.png",
                width: 16.w,
              ),
            ),
          ),
      ],
      if (isMe) ...[
        SizedBox(width: 8.w),
        Visibility(
          visible: message.sentStatus == RCIMIWSentStatus.sending,
          child: Container(
            margin: EdgeInsets.only(top: 10.h),
            child: CupertinoActivityIndicator(
              radius: 8.w,
            ),
          ),
        ),
        Visibility(
          visible: message.sentStatus == RCIMIWSentStatus.failed,
          child: Container(
            margin: EdgeInsets.only(top: 10.h),
            child: Icon(
              Icons.error,
              color: Colors.red,
              weight: 16.w,
            ),
          ),
        ),
      ]
    ];
    if (isMe) {
      childChildren = childChildren.reversed.toList();
    }
    var children = [
      ClipOval(
        child: CachedNetworkImage(
          width: 44.w,
          height: 44.w,
          imageUrl: avatar ?? "",
        ),
      ),
      SizedBox(width: 10.w),
      Expanded(
        child: Row(
          mainAxisAlignment:
              isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
          children: childChildren,
        ),
      ),
    ];
    if (isMe) {
      children = children.reversed.toList();
    }
    return Container(
      padding: EdgeInsets.only(
        left: 18.w,
        right: 18.w,
        bottom: 15.h,
        top: 15.h,
      ),
      child: Row(
        mainAxisAlignment:
            isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: children,
      ),
    );
  }

  Widget _content(RCIMIWMessage message, bool isMe) {
    switch (message.messageType!) {
      case RCIMIWMessageType.text:
        return _textMessage(message, isMe);
      case RCIMIWMessageType.voice:
        // TODO: Handle this case.
        return _voiceMessage(message, isMe);
      case RCIMIWMessageType.image:
        // TODO: Handle this case.
        return _imageMessage(message, isMe);
      case RCIMIWMessageType.sight:
        // TODO: Handle this case.
        break;
      default:
        return const SizedBox.shrink();
    }
    return const SizedBox.shrink();
  }

  Widget _textMessage(RCIMIWMessage message, bool isMe) {
    var textMessage = message as RCIMIWTextMessage;
    var translationStatus = textMessage.expansion?["translationStatus"] ?? 0;
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      constraints: BoxConstraints(
        maxWidth: 180.w,
      ),
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(8.w),
          bottomRight: Radius.circular(8.w),
          topLeft: isMe ? Radius.circular(8.w) : const Radius.circular(0),
          topRight: isMe ? const Radius.circular(0) : Radius.circular(8.w),
        ),
        color: isMe ? const Color(0xffffbc60) : Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            textMessage.text ?? "",
            style: TextStyle(
              color: isMe ? Colors.white : textColorBlack,
              fontSize: 14.sp,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w400,
            ),
          ),
          if (translationStatus == 1 || translationStatus == 2) ...[
            SizedBox(height: 12.h),
            Container(
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    color: const Color(0xffcccccc),
                    width: 0.5.w,
                  ),
                ),
              ),
              child: Padding(
                padding: EdgeInsets.only(top: 12.h),
                child: Visibility(
                  visible: translationStatus == 2,
                  replacement: CupertinoActivityIndicator(
                    radius: 8.w,
                  ),
                  child: Text(
                    textMessage.extra ?? "",
                    style: TextStyle(
                      color: isMe ? Colors.white : textColorBlack,
                      fontSize: 14.sp,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),
              ),
            ),
          ]
        ],
      ),
    );
  }

  Widget _imageMessage(RCIMIWMessage message, bool isMe) {
    var imageMsg = message as RCIMIWImageMessage;
    if(imageMsg.local != null) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(12.w),
        child: Image.file(
          File(imageMsg.local!),
          width: 158.w,
          fit: BoxFit.cover,
        ),
      );
    }
    return ClipRRect(
      borderRadius: BorderRadius.circular(12.w),
      child: CachedNetworkImage(
        imageUrl: imageMsg.remote ?? "",
        width: 158.w,
        fit: BoxFit.cover,
      ),
    );
  }

  Widget _voiceWidget() {
    return Obx(() {
      if (state.voicing.value == false) {
        return const SizedBox.shrink();
      }
      return Container(
          color: Colors.black.withOpacity(0.6),
          width: double.infinity,
          child: Obx(() {
            var valid = state.voiceValid.value;
            return Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Container(
                  height: 231.h,
                  alignment: Alignment.center,
                  child: Visibility(
                    visible: valid,
                    replacement: Image.asset(
                      "images/icon_voice_cancel.png",
                      width: 131.w,
                    ),
                    child: SizedBox(
                      width: 131.w,
                      child: const SVGASimpleImage(
                        assetsName: "images/sound.svga",
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 55.h),
                Text(
                  "Release ${valid ? "Send" : "Cancel"}",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 20.h),
                ClipPath(
                  clipper: _VoiceClipper(),
                  child: Container(
                    width: 375.w,
                    height: 158.h,
                    color: Colors.white,
                    padding:
                        EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
                    child: Center(
                      child: Image.asset(
                        "images/icon_voice_btn${valid ? "" : "_cancel"}.png",
                        width: 62.w,
                      ),
                    ),
                  ),
                )
              ],
            );
          }));
    });
  }

  Widget _voiceMessage(RCIMIWMessage message, bool isMe) {
    var child = [
      Image.asset(
        "images/icon_voice_${isMe ? "right" : "left"}.png",
        width: 20.w,
      ),
      SizedBox(width: 5.w),
      Text(
        "${(message as RCIMIWVoiceMessage).duration}''",
        style: TextStyle(
          color: isMe ? Colors.white : textColorBlack,
          fontSize: 16.sp,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w400,
        ),
      ),
    ];
    if (isMe) {
      child = child.reversed.toList();
    }
    return GestureDetector(
      onTap: () {
        logic.clickMessage(message);
      },
      child: Container(
        margin: EdgeInsets.only(top: 10.h),
        constraints: BoxConstraints(
          maxWidth: 180.w,
        ),
        padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(8.w),
            bottomRight: Radius.circular(8.w),
            topLeft: isMe ? Radius.circular(8.w) : const Radius.circular(0),
            topRight: isMe ? const Radius.circular(0) : Radius.circular(8.w),
          ),
          color: isMe ? const Color(0xffffbc60) : Colors.white,
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: child,
        ),
      ),
    );
  }
}

class _VoiceClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    var width = size.width;
    var height = size.height;
    path.lineTo(0, 30.h);
    path.quadraticBezierTo(width / 2, -30.h, width, 30.h);
    path.lineTo(width, height);
    path.lineTo(0, height);
    return path;
  }

  @override
  bool shouldReclip(_VoiceClipper oldClipper) {
    return true;
  }
}
